import request, { SearchResult } from '@/util/request';
import type { ApiResponse } from '@/types/note/note';
import { PageResult } from '@/components/Pagination.vue';
import { Chapter, CourseComment, CourseDetail, CourseDifficulty, CourseLabel, CourseResource, CourseType, CusStudyGroup, Exercises, Homework, HomeworkExercises, KnowledgePoint, Lessons, LessonsResource, PublishHomework, Question } from '@/types/Course';
import { userApi } from '../Users';
import { c } from 'vite/dist/node/types.d-aGj9QkWt';


// 课程公开内容
export interface CourseShow {
	courseId: number;
	courseName: string;
	courseDifficultyId: number;
	coursePicFileId: number;
	courseType: string;
	courseDescription: string;
	createDate: Date;
	createBy: number;
	collect?: boolean; // 收藏
	coverPath?: string;
}

// 查找课程
export interface FindCourse {
	courseId?: number,
	courseDifficulty?: CourseDifficulty,
	courseName?: string,
	courseType?: CourseType[],
	courseLabel?: CourseLabel[],
	pageNum?: number,
	pageSize?: number
}

// 新建课程
export interface NewCourse {
	courseName: string,
	courseDifficultyId: number,
	courseDescription: string,
	userId: 2,
	courseType: any[],
	courseLabel: any[],
	coverData: string,
}

// 更新章节
export interface UpdateLesson {
	lessonsId: number,
	lessonName: string,
	displayOrder: number
}
export interface UpdateChapter {
	chapterId: number,
	chapterName: string,
	displayOrder: number,
	lessons: UpdateLesson[]
}
export interface EditorChapter {
	courseId: number,
	chapters: UpdateChapter[]
}

export interface DataList<T> {
    length: number;
    data: T[];
}

export const courseTypeApi = {
	// 获取所有课程类型
	getType : async (): Promise<CourseType[]> => {
		try {
			const response = await request.post<ApiResponse<CourseType[]>>('course/overt/type/findType');
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取类型列表下的所有标签
	getLabelByList : async (typeIdList: number[]): Promise<CourseLabel[]> => {
		try {
			const response = await request.post<ApiResponse<CourseLabel[]>>('course/overt/type/findLabelByTypeList', {
				typeIdList: typeIdList
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
    // 获取课程难度
    getDifficulty: async (): Promise<CourseDifficulty[]> => {
        try {
            const response = await request.post<ApiResponse<CourseDifficulty[]>>('course/overt/type/findDifficulty', {
                
            });
            return response.data.data;
        } catch (error) {
            throw error;
        }
    },
}

export const courseDetailsApi = {
	// 课程介绍
	introduce: {
		// 获取课程介绍文本
		getText: async (courseId: number): Promise<ApiResponse<DataList<string>>> => {
			try {
				const response = await request.post<ApiResponse<DataList<string>>>('course/overt/getIntroduceText', {
					courseId: courseId
				});
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		// 设置课程介绍文本
		setText: async (courseId: number, courseIntroduce: string): Promise<ApiResponse<DataList<CourseShow>>> => {
			try {
				const response = await request.post<ApiResponse<DataList<CourseShow>>>('course/details/introduce/setText', {
					courseId: courseId,
					courseIntroduce: courseIntroduce
				});
				return response.data;
			} catch (error) {
				throw error;
			}
		},
	},
}

export const courseApi = {
	// 获取课程列表
	findCourse : async (findCourse: FindCourse): Promise<SearchResult<PageResult<CourseShow>>> => {
		try {
            console.log(findCourse)
            let findCourseData = {
                courseId: findCourse.courseId,
                courseName: findCourse.courseName,
                courseType: findCourse.courseType?.map(item => item.typeId),
                courseLabel: findCourse.courseLabel?.map(item => item.labelId),
                courseDifficulty: findCourse.courseDifficulty?.difficultyId,
				pageNum: findCourse.pageNum,
				pageSize: findCourse.pageSize
            }
            console.log(findCourseData)
			const response = await request.post<ApiResponse<SearchResult<PageResult<CourseShow>>>>('course/overt/findCourse', findCourseData);
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取热门课程
	findHotCourse: async (): Promise<CourseShow[]> => {
		try {
			const response = await request.post<ApiResponse<CourseShow[]>>('course/overt/findHotCourse');
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取课程信息
	findCourseInfo: async (courseId: number, detailed: number = 0): Promise<CourseDetail> => {
		try {
			const response = await request.post<ApiResponse<CourseDetail>>('course/overt/findCourseInfo', {
				courseId: courseId,
				detailed: detailed
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取课程权限
	getMemberPermission: async (courseId: number): Promise<number> => {
		try {
			
			const userData = await userApi.getLoginUserData();
			const response = await request.post<ApiResponse<number>>('course/getMemberPermission', {
				courseId: courseId,
				memberId: userData?.userId
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 章节
	chapter: {
		// 获取章节列表
		getList: async (courseId: number): Promise<ApiResponse<Chapter[]>> => {
			try {
				const response = await request.post<ApiResponse<Chapter[]>>('course/overt/getChapterList', {
					courseId: courseId
				});
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		getChapter: async (chapterId: number): Promise<ApiResponse<Chapter>> => {
			try {
				const response = await request.post<ApiResponse<Chapter>>('course/overt/getChapterInfo', {
					chapterId: chapterId
				});
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		updateChapter: async (editorChapter: EditorChapter): Promise<Boolean> => {
			try {
				const response = await request.post<ApiResponse<Boolean>>('course/chapter/update', editorChapter);
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		// 课时
		lessons: {
			// 获取课时列表
			getList: async (chapterId: number): Promise<ApiResponse<Lessons[]>> => {
				try {
					const response = await request.post<ApiResponse<Lessons[]>>('course/overt/getLessonList', {
						chapterId: chapterId
					});
					return response.data;
				} catch (error) {
					throw error;
				}
			},
			getLesson: async (lessonsId: number): Promise<ApiResponse<Lessons>> => {
				try {
					const response = await request.post<ApiResponse<Lessons>>('course/overt/getLessonInfo', {
						lessonsId: lessonsId
					});
					return response.data;
				} catch (error) {
					throw error;
				}
			},
			updateLessonResource: async (lessonsId: number, lessonsResourceList: LessonsResource[]): Promise<ApiResponse<boolean>> => {
				try {
					const response = await request.post<ApiResponse<boolean>>('course/chapter/updateLessonResource', {
						lessonsId: lessonsId,
						lessonsResourceList: lessonsResourceList
					});
					return response.data;
				}catch (error) {}
 			},
			getLessonResource: async (lessonsId: number): Promise<ApiResponse<LessonsResource[]>> => {
				try {
					const response = await request.post<ApiResponse<LessonsResource[]>>('course/chapter/getLessonResource', {
						lessonsId: lessonsId
					});
					return response.data;
				} catch (error) {
					throw error;
				}
			},
			uploadFile: async (file: File, resourceId: number, onProgress?: (progress: number) => void): Promise<number> => {
				try {
					const response = await request.upload<ApiResponse<number>>('course/chapter/uploadLessonsResourceFile', file, {resource: resourceId}, onProgress);
					return response.data.data;
				} catch (error) {
					throw error;
				}
			},
		},
		// 知识点
		knowledge: {
			// 获取知识点
			getKnowledgePoint: async (courseId: number, chapterId: number): Promise<ApiResponse<KnowledgePoint[]>> => {
				try {
					const response = await request.post<ApiResponse<KnowledgePoint[]>>('course/overt/getKnowledges', {
						courseId: courseId, chapterId: chapterId
					});
					return response.data;
				} catch (error) {
					throw error;
				}
			},
			// 添加知识点
			addKnowledgePoint: async (knowledge: KnowledgePoint): Promise<ApiResponse<boolean>> => {
				try {
					const response = await request.post<ApiResponse<boolean>>('course/chapter/createKnowledge', knowledge);
					return response.data;
				} catch (error) {
					throw error;
				}
			},
			// 移除知识点
			removeKnowledgePoint: async (knowledge: KnowledgePoint): Promise<ApiResponse<boolean>> => {
				try {
					const response = await request.post<ApiResponse<boolean>>('course/chapter/removeKnowledge', knowledge);
					return response.data;
				} catch (error) {
					throw error;
				}
			},
		},
	},
	// 资源
	resource: {
	},
	// 评论
	comment: {
		getList: async (courseId: number): Promise<CourseComment[]> => {
			try {
				const response = await request.post<ApiResponse<CourseComment[]>>('course/overt/getCourseComment', {
					courseId: courseId
				});
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		addComment: async (comment: CourseComment): Promise<boolean> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/commentCourse', comment);
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		deleteComment: async (comment: CourseComment): Promise<boolean> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/deleteComment', comment);
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
	},
	// 班级
	courseClass: {
		// 获取班级列表
		getClassList: async (courseId: number): Promise<CusStudyGroup[]> => {
			try {
				const response = await request.post<ApiResponse<CusStudyGroup[]>>('course/getClassList', {
					courseId: courseId
				});
				return response.data.data;
			} catch (error) {
				throw error;
			}
		}
	},
	// 创建课程
	createCourse: async (course: NewCourse): Promise<ApiResponse<CourseShow>> => {
		try {
			const response = await request.post<ApiResponse<CourseShow>>('course/create', course);
			return response.data;
		} catch (error) {
			throw error;
		}
	},
	// 加入班级
	joinCourse: async (courseId: number): Promise<ApiResponse<DataList<CourseShow>>> => {
		try {
			const response = await request.post<ApiResponse<DataList<CourseShow>>>('course/joinCourse', {
				courseId: courseId
			});
			return response.data;
		} catch (error) {
			throw error;
		}
	},
	// 收藏课程
	collectCourse: async (courseId: number): Promise<ApiResponse<number>> => {
		try {
			const response = await request.post<ApiResponse<number>>('course/collectCourse', {
				courseId: courseId
			});
			return response.data;
		} catch (error) {
			throw error;
		}
	},
	// 取消收藏课程
	cancelCollectCourse: async (courseId: number): Promise<ApiResponse<number>> => {
		try {
			const response = await request.post<ApiResponse<number>>('course/cancelCollectCourse', {
				courseId: courseId
			});
			return response.data;
		} catch (error) {
			throw error;
		}
	},
};

export const homeworkApi = {
	// 获取作业列表
	getHomeworkList: async (targetId: number, homeworkType?: string): Promise<Homework[]> => {
		try {
			const response = await request.post<ApiResponse<Homework[]>>('homework/getHomeworkList', {
				targetId: targetId,
				homeworkType: homeworkType
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 设置作业
	setHomework: async (homework: Homework, homeworkExercises: HomeworkExercises[]): Promise<number> => {
		try {
			homework.exercises = null;
			homeworkExercises.map(exercise => {
				exercise.exerciseInfo = null;
			});
			const response = await request.post<ApiResponse<number>>('homework/setHomework', {
				homework: homework,
				homeworkExercises: homeworkExercises
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 删除作业
	deleteHomework: async (homework: Homework): Promise<number> => {
		try {
			const response = await request.post<ApiResponse<number>>('course/homework/deleteHomework', homework);
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 发布
	publish: {
		// 发布作业
		publishHomework: async (publishHomework: PublishHomework): Promise<number> => {
			try {
				const response = await request.post<ApiResponse<number>>('homework/publishHomework', publishHomework);
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		// 获取作业列表
		getHomeworkList: async (targetId?: number, homeworkType?: string): Promise<PublishHomework[]> => {
			try {
				const response = await request.post<ApiResponse<PublishHomework[]>>('homework/getPublishHomeworkList', {
					targetId: targetId,
					homeworkType: homeworkType
				});
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		getPublishHomeworkByHomeworkId: async (homeworkId: number): Promise<PublishHomework[]> => {
			try {
				const response = await request.post<ApiResponse<PublishHomework[]>>('homework/getPublishHomeworkByHomeworkId', {
					homeworkId: homeworkId
				});
				return response.data.data;
			} catch (error) {
				throw error;
			} 
		},
		getPublishHomework: async (publishId: number): Promise<PublishHomework> => {
			try {
				const response = await request.post<ApiResponse<PublishHomework>>('homework/getPublishHomework', {
					publishId: publishId
				});
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		// 修改作业
		updateHomework: async (homeworkId: number, homework: Homework): Promise<ApiResponse<boolean>> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/homework/updateHomework', {
					homeworkId: homeworkId,
					homework: homework
				});
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		// 提交作业
		submitHomework: async (homeworkId: number, userId: number, exerciseId: number, exerciseScore: number): Promise<ApiResponse<boolean>> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/homework/submitHomework', {
					homeworkId: homeworkId,
					userId: userId,
					exerciseId: exerciseId,
					exerciseScore: exerciseScore
				})
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		// 取消发布
		cancelPublish: async (exerciseId: number): Promise<ApiResponse<boolean>> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/exercises/cancelPublish', {
					exerciseId: exerciseId
				})
				return response.data;
			} catch (error) {
				throw error;
			}
		}
	}
};

export const exercisesApi = {
	// 获取习题列表
	getExercises: async (courseId: number, knowledgeId: number, pageNum: number, pageSize: number): Promise<PageResult<Exercises>> => {
		try {
			const response = await request.post<ApiResponse<PageResult<Exercises>>>('course/exercise/getExercises', {
				courseId: courseId,
				knowledgeId: knowledgeId,
				pageNum: pageNum,
				pageSize: pageSize
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 添加习题
	addExercises: async (exercises: Exercises): Promise<ApiResponse<number>> => {
		try {
			const response = await request.post<ApiResponse<number>>('course/exercise/addExercises', exercises);
			return response.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取习题详情
	getExercisesById: async (exerciseId: number): Promise<ApiResponse<Exercises>> => {
		try {
			const response = await request.post<ApiResponse<Exercises>>('course/exercise/getExercisesById', {
				exercisesId: exerciseId
			});
			return response.data;
		} catch (error) {
			throw error;
		}
	},
	updateExercises: async (exercises: Exercises): Promise<boolean> => {
		try {
			const response = await request.post<ApiResponse<boolean>>('course/exercise/updateExercises', exercises);
			console.log(response.data);
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	// 获取习题题目
	questions: {
		// 添加习题题目
		addQuestions: async (questions: Question[]): Promise<ApiResponse<boolean>> => {
			try {
				const response = await request.post<ApiResponse<boolean>>('course/exercise/question/addQuestions', questions);
				return response.data;
			} catch (error) {
				throw error;
			}
		},
		// 获取习题题目
		getQuestions: async (exerciseId: number, pageNum: number, pageSize: number): Promise<PageResult<Question>> => {
			try {
				const response = await request.post<ApiResponse<PageResult<Question>>>('course/exercise/question/getQuestions', {
					exerciseId: exerciseId,
					pageNum: pageNum,
					pageSize: pageSize
				});
				return response.data.data;
			} catch (error) {
				throw error;
			}
		}
	}
}

export const resourceApi = {
	getResourceList: async (courseId: number): Promise<CourseResource[]> => {
		try {
			const response = await request.post<ApiResponse<CourseResource[]>>('course/overt/getResourceList', {
				courseId: courseId
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	createResource: async (resource: CourseResource): Promise<number> => {
		try {
			const response = await request.post<ApiResponse<number>>('course/resource/create', resource);
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	getResourceInfo: async (resourceId: number): Promise<CourseResource> => {
		try {
			const response = await request.post<ApiResponse<CourseResource>>('course/resource/getResourceInfo', {
				resourceId: resourceId
			});
			return response.data.data;
		} catch (error) {
			throw error;
		}
	},
	files: {
		upload: async (file: File, resourceId: number, onProgress?: (progress: number) => void): Promise<number> => {
			try {
				const response = await request.upload<ApiResponse<number>>('course/resource/upload', file, {resource: resourceId}, onProgress);
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		getProgress: async (sessionId: string): Promise<number> => {
			try {
				const response = await request.getProgress(sessionId);
				if (response.data.code != 200) {
					throw new Error('获取进度失败');
				}
				return response.data.data;
			} catch (error) {
				throw error;
			}
		},
		download: async (fileId: number, filename?: string): Promise<void> => {
			try {
				await request.download('course/resource/download', filename, {
					fileId: fileId
				});
			} catch (error) {
				throw error;
			}
		}
	},
	getResource: async (resourceId: number): Promise<any[]> => {
		try {
			switch (resourceId) {
				case 2:
					return [{
						id: 1,
						name: '第二节课课程PPT',
						type: 'ppt',
						size: '9MB',
						uploadTime: '2025-03-01 12:10:00',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '第二节课课程文档',
						type: 'word',
						size: '8MB',
						uploadTime: '2025-03-01 12:10:00',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '第二节课课程源码文件',
						type: 'zip',
						size: '15MB',
						uploadTime: '2025-03-01 12:10:00',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '第二节课课程源码文件',
						type: 'rar',
						size: '13MB',
						uploadTime: '2025-03-01 12:10:01',
						resourceUrl: 'https://www.baidu.com'
					}]
				case 1:
					return [{
						id: 1,
						name: '课程PPT',
						type: 'ppt',
						size: '10MB',
						uploadTime: '2025-03-01 12:00:00',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '课程源码文件',
						type: 'zip',
						uploadTime: '2025-03-01 12:00:00',
						size: '21MB',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '课程源码文件',
						type: 'rar',
						size: '18MB',
						uploadTime: '2025-03-01 12:00:00',
						resourceUrl: 'https://www.baidu.com'
					},{
						id: 1,
						name: '课程文档',
						type: 'word',
						size: '13MB',
						uploadTime: '2025-03-01 12:00:00',
						resourceUrl: 'https://www.baidu.com'
					}]
				default:
					return []
			}
		} catch (error) {
			throw error;
		}
	}
}